package io.kiki.sba.registry.server.metadata.resource;


import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.console.PersistenceData;
import io.kiki.sba.registry.common.model.console.PersistenceDataBuilder;
import io.kiki.sba.registry.common.model.constants.ValueConstants;
import io.kiki.sba.registry.common.model.metaserver.CompressDatumSwitch;
import io.kiki.sba.registry.common.model.metaserver.CompressPushSwitch;
import io.kiki.sba.registry.common.model.metaserver.ProvideDataChangeEvent;
import io.kiki.sba.registry.core.model.Result;
import io.kiki.sba.registry.server.metadata.provide.data.DefaultProvideDataNotifier;
import io.kiki.sba.registry.server.metadata.provide.data.ProvideDataService;
import io.kiki.sba.registry.server.metadata.resource.filter.LeaderAwareRestController;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.OperationStatus;
import io.kiki.sba.registry.util.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;
import java.util.HashSet;

@Path("compress")
@LeaderAwareRestController
public class CompressResource {
    private static final Logger logger = LoggerFactory.getLogger(CompressResource.class);

    @Autowired
    ProvideDataService provideDataService;

    @Autowired
    DefaultProvideDataNotifier provideDataNotifier;

    @POST
    @Path("push/switch")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result setPushSwitch(CompressPushSwitch compressPushSwitch) {
        PersistenceData persistenceData = PersistenceDataBuilder.createPersistenceData(ValueConstants.COMPRESS_PUSH_SWITCH_DATA_ID, JsonUtils.writeValueAsString(compressPushSwitch));
        Result result = new Result();
        boolean ret;
        try {
            ret = provideDataService.saveProvideData(persistenceData);
            logger.info("push compressed {} to DB result {}", compressPushSwitch, ret);
        } catch (Throwable e) {
            logger.error("push compressed {} to DB result error", compressPushSwitch, e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        if (ret) {
            ProvideDataChangeEvent provideDataChangeEvent = new ProvideDataChangeEvent(ValueConstants.COMPRESS_PUSH_SWITCH_DATA_ID, persistenceData.getVersion(), new HashSet<>(Arrays.asList(Node.NodeType.client_interface)));
            provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent);
        }
        result.setSuccess(ret);
        return result;
    }

    @GET
    @Path("push/state")
    @Produces(MediaType.APPLICATION_JSON)
    public CompressPushSwitch getPushSwitch() {
        DBResponse<PersistenceData> response = provideDataService.queryProvideData(ValueConstants.COMPRESS_PUSH_SWITCH_DATA_ID);
        if (response.getOperationStatus() == OperationStatus.notfound || StringUtils.isBlank(response.getEntity().getData())) {
            return CompressPushSwitch.defaultSwitch();
        }
        return JsonUtils.read(response.getEntity().getData(), CompressPushSwitch.class);
    }

    @POST
    @Path("datum/switch")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result setDatumSwitch(CompressDatumSwitch compressDatumSwitch) {
        PersistenceData persistenceData = PersistenceDataBuilder.createPersistenceData(ValueConstants.COMPRESS_DATUM_SWITCH_DATA_ID, JsonUtils.writeValueAsString(compressDatumSwitch));
        Result result = new Result();
        boolean ret;
        try {
            ret = provideDataService.saveProvideData(persistenceData);
            logger.info("datum compressed {} to DB result {}", compressDatumSwitch, ret);
        } catch (Throwable e) {
            logger.error("datum compressed {} to DB result error", compressDatumSwitch, e);
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        if (ret) {
            ProvideDataChangeEvent provideDataChangeEvent = new ProvideDataChangeEvent(ValueConstants.COMPRESS_DATUM_SWITCH_DATA_ID, persistenceData.getVersion(), new HashSet<>(Arrays.asList(Node.NodeType.data_store)));
            provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent);
        }
        result.setSuccess(ret);
        return result;
    }

    @GET
    @Path("datum/state")
    @Produces(MediaType.APPLICATION_JSON)
    public CompressDatumSwitch getDatumSwitch() {
        DBResponse<PersistenceData> response = provideDataService.queryProvideData(ValueConstants.COMPRESS_DATUM_SWITCH_DATA_ID);
        if (response.getOperationStatus() == OperationStatus.notfound || StringUtils.isBlank(response.getEntity().getData())) {
            return CompressDatumSwitch.defaultSwitch();
        }
        return JsonUtils.read(response.getEntity().getData(), CompressDatumSwitch.class);
    }
}
